// src/items/items.controller.ts
import {Body, Controller, Get, ParseFilePipeBuilder, Post, UploadedFile, UseInterceptors} from '@nestjs/common';
import { DimensionService } from './dimension.service';
import {CreateMessagePipe} from "../../common/pipes/createmessage.pipe";
import {AddDemoDto, ImportDimensionDto, UpdateDto} from "./dto/req-demo.dto";
import {RepeatSubmit} from "../../common/decorators/repeat-submit.decorator";
import {ApiException} from "../../common/exceptions/api.exception";
import {ExcelService} from "../common/excel/excel.service";
import {FileInterceptor} from "@nestjs/platform-express";

@Controller('dimension')
export class DimensionController {
  constructor(private readonly dimensionService: DimensionService, private readonly excelService: ExcelService) {}

  @Post('detail')
  @RepeatSubmit()
  async findAll(@Body(CreateMessagePipe) addDemoDto: AddDemoDto) {
    return this.dimensionService.findItemById(addDemoDto.projectId);
  }

  @Post('update')
  @RepeatSubmit()
  async updateById(@Body(CreateMessagePipe) updateDto: UpdateDto) {
    return this.dimensionService.update(updateDto);
  }

  /* 用户导入 */
  @Post('importData')
  @RepeatSubmit()
  @UseInterceptors(FileInterceptor('file'))
  async importData(
    @UploadedFile(
      new ParseFilePipeBuilder()
        .addMaxSizeValidator({
          maxSize: 1024 * 1024 * 5,
        })
        .addFileTypeValidator({
          fileType:
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        })
        .build({
          exceptionFactory: (error) => {
            throw new ApiException(
              '文件格式错误！ 文件最大为5M，且必须是 xlsx 格式',
            );
          },
        }),
    )
      file: Express.Multer.File,
  ) {
    const data = await this.excelService.import<ImportDimensionDto>(
      ImportDimensionDto,
      file,
    );
    await this.dimensionService.importData(data);
  }
}
